package unit

import (
	"context"

	"gitee.com/bitwormhole/cloud-aliyun-api/aliyun/openapi"
	"gitee.com/bitwormhole/cloud-aliyun-api/aliyun/openapi/alidns"
	"github.com/starter-go/units"
)

// DNSUnit ...
type DNSUnit struct {

	//starter:component
	_as func(units.Units) //starter:as(".")

	OpenAPI openapi.Service //starter:inject("#")

}

func (inst *DNSUnit) _impl() units.Units { return inst }

// Units ...
func (inst *DNSUnit) Units(list []*units.Registration) []*units.Registration {

	list = append(list, &units.Registration{
		Name:     "test-alidns-DescribeDomainInfo",
		Enabled:  true,
		Priority: 0,
		Test:     inst.testDescribeDomainInfo,
	})

	list = append(list, &units.Registration{
		Name:     "test-alidns-DescribeDomainRecords",
		Enabled:  true,
		Priority: 0,
		Test:     inst.testDescribeDomainRecords,
	})

	list = append(list, &units.Registration{
		Name:     "test-alidns-AddDomainRecord",
		Enabled:  true,
		Priority: 0,
		Test:     inst.testAddDomainRecord,
	})

	list = append(list, &units.Registration{
		Name:     "test-alidns-DeleteDomainRecord",
		Enabled:  true,
		Priority: 0,
		Test:     inst.testDeleteDomainRecord,
	})

	return list
}

func (inst *DNSUnit) testDescribeDomainInfo() error {

	ctx := context.Background()
	task := new(alidns.DescribeDomainInfo)
	task.DomainName = "puyakeji.com"

	client, err := inst.OpenAPI.GetDefaultClient()
	if err != nil {
		return err
	}

	err = client.Execute(ctx, task)
	if err != nil {
		return err
	}

	return nil
}

func (inst *DNSUnit) testDescribeDomainRecords() error {

	ctx := context.Background()
	task := new(alidns.DescribeDomainRecords)
	task.DomainName = "puyakeji.com"

	client, err := inst.OpenAPI.GetDefaultClient()
	if err != nil {
		return err
	}

	err = client.Execute(ctx, task)
	if err != nil {
		return err
	}

	return nil
}

func (inst *DNSUnit) testAddDomainRecord() error {

	ctx := context.Background()
	task := new(alidns.AddDomainRecord)
	task.DomainName = "puyakeji.com"
	task.RR = "test-240221-2"
	task.Type = "TXT"
	task.Value = "this is a test from go-lang"

	client, err := inst.OpenAPI.GetDefaultClient()
	if err != nil {
		return err
	}

	err = client.Execute(ctx, task)
	if err != nil {
		return err
	}

	return nil
}

func (inst *DNSUnit) testDeleteDomainRecord() error {

	ctx := context.Background()
	task := new(alidns.DeleteDomainRecord)
	task.RecordID = "880149145895131136"

	client, err := inst.OpenAPI.GetDefaultClient()
	if err != nil {
		return err
	}

	err = client.Execute(ctx, task)
	if err != nil {
		return err
	}

	return nil
}
